package com.san.report.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.san.base.dao.DictDao;
import com.san.base.domain.DictDO;
import com.san.base.domain.Tree;
import com.san.common.utils.BuildTree;
import com.san.common.utils.Constant;
import com.san.report.dao.ReportRoleDao;
import com.san.report.domain.ReportRoleDO;
import com.san.report.service.ReportRoleService;

@Service
public class ReportRoleServiceImpl implements ReportRoleService {

	@Autowired
	private DictDao dictMapper;

	@Autowired
	ReportRoleDao reportRoleMapper;

	@Override
	public int doEdit(Object obj) throws Exception {
		ReportRoleDO reportRole = (ReportRoleDO) obj;
		List<Long> dictIds = reportRole.getDictIds();
		Long roleId = reportRole.getDeptId();
		reportRoleMapper.removeByDeptId(roleId);
		List<ReportRoleDO> rms = new ArrayList<>();
		for (Long dictId : dictIds) {
			ReportRoleDO rmDo = new ReportRoleDO();
			rmDo.setDeptId(roleId);
			rmDo.setDictId(dictId);
			rms.add(rmDo);
		}
		if (rms.size() > 0) {
			reportRoleMapper.batchSave(rms);
		}
		
		return 0;
	}

	@Override
	public Tree<DictDO> getTree(Long roleId) throws Exception {
		Map<String, Object> param = new HashMap<>(16);
		//param.put("type", Constant.DICT_TYPE_CLASS);
		List<DictDO> dictDOs = dictMapper.list(param);

		List<Long> dictIds = reportRoleMapper.listDictIdByDeptId(roleId);

		List<Long> temp = dictIds;
		for (DictDO dictDO : dictDOs) {
			if (temp.contains(dictDO.getParentId())) {
				dictIds.remove(dictDO.getParentId());
			}
		}

		List<Tree<DictDO>> trees = new ArrayList<Tree<DictDO>>();
		for (DictDO dictDO : dictDOs) {
			Tree<DictDO> tree = new Tree<DictDO>();
			tree.setId(dictDO.getId().toString());
			tree.setParentId(dictDO.getParentId().toString());
			tree.setText(dictDO.getName());
			Map<String, Object> state = new HashMap<>(16);
			Long id = dictDO.getId();

			if (dictIds.contains(id)) {
				state.put("selected", true);
			} else {
				state.put("selected", false);
			}

			tree.setState(state);
			trees.add(tree);
		}
		// Constant.DICT_BUSI_TYPE_ID 业务类型ID
		Tree<DictDO> t = BuildTree.build(trees, true, Constant.DICT_BUSI_TYPE_ID);
		return t;
	}

	@Override
	public List<Long> dictList(Long deptId) throws Exception {
		List<Long> dictIds = reportRoleMapper.dictList(deptId);
		return dictIds;
	}

}
